package com.liangjie.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 1、获取method参数，它是用户想调用的方法 2、把方法名称变成Method的实例对象 3、通过invoke()来调用
		 */
		String methodName = request.getParameter("method");
		Method method = null;
		try {
			method = this.getClass().getMethod(methodName,
					HttpServletRequest.class, HttpServletResponse.class);
		} catch (Exception e) {
			throw new RuntimeException("调用的" + methodName + "不存在！", e);
		}
		try {
			String result = method.invoke(this, request, response).toString();
			if (result != null && !result.trim().isEmpty()) {
				String[] results = result.split(":");
				if (results[0].equals("f")) {
					request.getRequestDispatcher(results[1]).forward(request,
							response);
				} else if (results[0].equals("r")) {
					response.sendRedirect(request.getContextPath() + results[1]);
				}
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
